function [ data, move_data ] = FUN_PPG_generationMotion( time, sampletime, frequency, amplitude, noise )
%[ data, t ] = 
%FUN_PPG_generation
%   Time : 2016-07-01 13:32:43
%   Version:V0.1
%   Author:@hiyangdong

%% function preparation and preproccess
if nargin<5
    noise = 1;
    if nargin < 4
        amplitude = 1;
        if nargin < 3
            frequency = 1.2;
            if nargin < 2
                sampletime = 0.01;
                if nargin < 1
                    time = 20;
                end
            end
        end
    end
end

%% Data preparation and preproccess
% sample time and frequency
% generate time and frequency sequence
period = 1/frequency;
size = fix(time/sampletime);
data = zeros(1,size);
ts = sampletime;
t = 0:ts:(size-1) * ts;             %time point
samplefreq = 1/sampletime;                          %sample frequency that unit is Hz
fs = samplefreq;
f = (0:(size-1))/size*fs;                   %frequency point

tp = [0,  0.2,  0.4,  0.45, 0.5,  0.6,  0.7,  0.8,  0.9  ]; % time period
dp = [0,  1.0,  0.6,  0.65, 0.6,  0.5,  0.35, 0.24, 0.12 ]; % data period
tr = [tp,tp+1,tp+2]*period;             % time repeat
dr = repmat(dp,1,3)*amplitude;          % data repeat
ti = 0:ts:(fix(3*fs*period)-1) * ts;
di = interp1(tr,dr,ti,'pchip');         % data interlp
ds = di(fix(fs*period)+1 : fix(2*fs*period));

data = repmat(ds,1,fix(size/length(ds)));
data = [data, ds(1:mod(size,length(ds)))];

% figure(1);
% plot(t,data);

if noise == 1
    % base line shift
    base_fn  = 0.1;
    for i=0 : fs/size : base_fn
        base_amp = rand*0.5;
        base_pha = rand*pi;
        base_data = base_amp*cos(2*pi*t*i/fs+base_pha);
        data = base_data + data;
    end
%     figure(2);plot(t,base_data);
%     figure(3);plot(t,data);
    % respiration
    resp_fn(1)  = 0.2;
    resp_fn(2)  = 0.4;
    
    resp_fr = resp_fn(1) + (resp_fn(2)-resp_fn(1))*rand;
    resp_amp = 0.2*rand;
    resp_pha = rand*pi;
    
    resp_data = resp_amp*cos(2*pi*t*resp_fr+resp_pha);
    data = resp_data + data;
%     figure(4);plot(t,resp_data);
%     figure(5);plot(t,data);
    % motion artifacts
    move_fn(1)  = 0.5;
    move_fn(2)  = 10;
    
    move_fm = move_fn(1) + (move_fn(2) - move_fn(1))*rand;
    move_data = zeros(1,size);
    for i = move_fm :fs/size: move_fm + 0.1
        move_amp = 0.5*rand;
        move_pha = rand*pi;
        move_temp = move_amp*cos(2*pi*t*i+move_pha);
        move_data = move_data + move_temp;
    end
    data = data +move_data;
% 	figure(6);plot(t,move_data);
%     figure(7);plot(t,data);
end
end

